/*
 图片预览上传插件
 poly 2017/4/5
 */
(function ($) {
    $.fn.uploadH5 = function (options) {
        var defaults = {
            max: 400, //最终图片最大尺寸
            preview: undefined, //预览显示对象，undefined则不需要预览
            filename: 'file[]', //intput[type=file]标签的name值
            defaultImg: 'null.png', //空图片时候，预览图片显示图
            //失误回调函数
            errCb: function (msg) {
                window._alert(msg);
            },

            uploadBtnCaption: '选择图片', //上传按钮显示标题
            uploadBtnCss: 'btn btn-mini btn-primary myUploadBtn',  //上传按钮显示样式
            reset: true, //是否需要恢复按钮
            resetBtnCaption: '恢复', //恢复按钮显示标题
            resetBtnCss: 'btn btn-mini btn-success myUploadBtn',  //恢复按钮显示样式

            submit: false, //是否需要单张图片上传
            submitBtnCaption: '上传', //单张图片上传按钮标题
            submitBtnCss: 'btn btn-mini btn-info myUploadBtn', //单张图片上传按钮样式
            saveKeyUrl: '', //保存上传图片key
            qiniuToken: '', //七牛服务器token
            qa: 0.92
        };
        var options = $.extend(defaults, options);
        return this.each(function () {
            $(this).hide();
            var fileCtr = $("<input type='file' style='display:none' name='" + options.filename + "'>");
            $(this).data("fileCtr", fileCtr).after(fileCtr);
            var btnCtr = $("<button type='button' class='" + options.uploadBtnCss + "'>" + options.uploadBtnCaption + "</button>");
            $(this).after(btnCtr);
            btnCtr.data("file", fileCtr).on("click", function () {
                $(this).data("file").click();
            });
            options.target = $(this);
            options.target.data("initValue", options.target.val());
            var source = $(this).data("fileCtr");
            //构造一个空白的canvas组件
            var myCanvas = source.data("myCanvas");
            if (myCanvas == undefined) { //初始化对应画布
                myCanvas = document.createElement("canvas");
                myCanvas.style.display = "none";
                source.data("myCanvas", myCanvas);
            }
            if (options.target.val() != "") {
                options.preview.attr("src", options.target.val());
            } else {
                options.preview.attr("src", options.defaultImg);
            }

            source.data("options", options);
            if (options.reset) {
                var btn = $("<button type='button' class='" + options.resetBtnCss + "'>" + options.resetBtnCaption + "</button>");
                btn.data("options", options);
                options.target.data("fileCtr").after(btn);
                btn.on("click", function () {
                    var options = $(this).data("options");
                    options.target.val(options.target.data("initValue"));
                    source.val(options.target.data("initValue"));
                    if (options.preview != undefined) {
                        if (options.target.val() != "") {
                            options.preview.attr("src", options.target.val());
                        } else {
                            options.preview.attr("src", options.defaultImg);
                        }
                    }
                });
            }

            if (options.submit) {
                var btn = $("<button type='button' class='" + options.submitBtnCss + "'>" + options.submitBtnCaption + "</button>");
                options.target.parent().append(btn);
                btn.on("click", function () {
                    var image_body = options.target.val();
                    image_body = image_body.slice(image_body.indexOf(',') + 1);
                    if (!image_body) {
                        options.errCb('请选择您需要上传的图片');
                        return;
                    }
                    if (!options.saveKeyUrl) {
                        options.errCb('图片上传地址不存在');
                        return;
                    }

                    var url = "http://up.qiniu.com/putb64/-1/";
                    var xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4) {
                            var qiniu_res = eval("(" + xhr.responseText + ")");
                            $.ajax({
                                url: options.saveKeyUrl,
                                type: 'post',
                                data: {
                                    image_name: options.filename,
                                    qiniu_key: qiniu_res['key']
                                },
                                dataType: 'json',
                                success: function (res) {
                                    options.errCb(res['msg']);
                                    //成功后清除图片
                                    if (!res.errorCode) {
                                        options.target.val('');
                                    }
                                }
                            });
                        }
                    };
                    xhr.open("POST", url, true);
                    xhr.setRequestHeader("Content-Type", "application/octet-stream");
                    xhr.setRequestHeader("Authorization", "UpToken " + options.qiniuToken);
                    xhr.send(image_body);
                });
            }

            //增加对应fileReader组件
            var reader = source.data("myCanvas_reader");
            if (reader == undefined) {
                reader = new FileReader();
                reader.onload = function (e) {
                    var image = new Image();
                    image.onload = function () {
                        if (options.max > 0) {
                            if (image.height > image.width) {
                                // 如果高度超标
                                if (image.height > options.max) {
                                    // 宽度等比例缩放 *=
                                    image.width *= options.max / image.height;
                                    image.height = options.max;
                                }
                            } else {
                                if (image.width > options.max) {
                                    // 宽度等比例缩放 *=
                                    image.height *= options.max / image.width;
                                    image.width = options.max;
                                }
                            }
                        }
                        var context = myCanvas.getContext("2d");
                        context.clearRect(0, 0, myCanvas.width, myCanvas.height); //清掉
                        myCanvas.width = image.width;
                        myCanvas.height = image.height;
                        context.drawImage(image, 0, 0, image.width, image.height);
                        if (options.preview != undefined) {
                            options.preview.attr('src', myCanvas.toDataURL('image/png'), options.qa);
                        }
                        options.target.attr("change", 0).val(myCanvas.toDataURL('image/png'), options.qa);
                    };
                    image.src = e.target.result;
                };
                source.data("myCanvas_reader", reader);
            }
            source.on("change", function () {
                var myCanvas = $(this).data("myCanvas"); //找出对应的画布
                var options = $(this).data("options");
                var reader = source.data("myCanvas_reader");
                if ($(this).val() == "") return;
                if (!this.files[0].type.match(/image.*/)) {
                    options.errCb("错误，请选择图片类型文件 ");
                    return;
                }
                reader.readAsDataURL(this.files[0]);
            });
        });
    };

})(jQuery);